package hxy.dragon.location_record;

import android.Manifest;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Point;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.text.Editable;
import android.text.InputFilter;
import android.view.Display;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.navigation.NavBackStackEntry;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

import com.alibaba.fastjson.JSONObject;
import com.ejlchina.okhttps.OkHttps;
import com.github.lany192.kv.KVUtils;
import com.google.android.material.snackbar.Snackbar;
import com.king.app.dialog.AppDialog;
import com.king.app.dialog.AppDialogConfig;
import com.king.app.updater.AppUpdater;
import com.kongzue.dialogx.DialogX;
import com.kongzue.dialogx.dialogs.FullScreenDialog;
import com.kongzue.dialogx.dialogs.TipDialog;
import com.kongzue.dialogx.dialogs.WaitDialog;
import com.kongzue.dialogx.interfaces.DialogLifecycleCallback;
import com.kongzue.dialogx.interfaces.OnBindView;
import com.tencent.mmkv.MMKV;

import java.util.Deque;

import hxy.dragon.location_record.databinding.ActivityMainBinding;
import hxy.dragon.location_record.tencent.LocationService;
import hxy.dragon.location_record.util.Constant;
import hxy.dragon.location_record.util.GpsUtil;
import hxy.dragon.location_record.util.Time;

import static android.Manifest.permission.ACCESS_BACKGROUND_LOCATION;
import static java.util.Objects.isNull;

public class MainActivity extends AppCompatActivity {

    private AppBarConfiguration appBarConfiguration;
    private ActivityMainBinding binding;
    private LocationService locationService;
    /**
     * 绑定服务
     */
    private ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            locationService = ((LocationService.LocalBinder) iBinder).getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            locationService = null;
        }
    };

    private static Context context;


    public static Context getAppContext() {
        return context;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = this;

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        setSupportActionBar(binding.toolbar);

        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
        Deque<NavBackStackEntry> backStack = navController.getBackStack();
        NavBackStackEntry pop = backStack.pop();

        appBarConfiguration = new AppBarConfiguration.Builder(navController.getGraph()).build();
        NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);

//        binding.fab.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                // 设置更新时间
////                long interval = intervals[i++ % intervals.length];
////
////                String timeValue = Time.desplay(interval);
////
////                Intent intent = new Intent(Constant.BroadCast.INTERVAL);
////                intent.putExtra(Constant.INTERVAL, interval);
////                sendBroadcast(intent);
//
//                Snackbar.make(view, "联系作者微信 aohanhongyi" , Snackbar.LENGTH_LONG)
//                        .setAction("Action", null).show();
//            }
//        });
        DialogX.init(context);

        MMKV.initialize(context);

        initPermissions();

        startLocationService();
        update();
    }

    private void update() {

        OkHttps.async("/api/v1/version")
                .addUrlPara("appId", 1).setOnException(e -> {
            Toast.makeText(getBaseContext(), "网络异常" + e.getMessage(), Toast.LENGTH_SHORT).show();
        }).setOnResponse(onResponse -> {
            int status1 = onResponse.getStatus();
            if (status1 == 200) {
                String response = onResponse.getBody().toString();
                JSONObject jsonObject = JSONObject.parseObject(response);
                JSONObject data1 = jsonObject.getJSONObject("data");
                boolean update = data1.getBoolean("lasted");
                String updateInfo = data1.getString("updateInfo");
                String downloadUrl = data1.getString("downloadUrl");
                if (update) {
                    // 这里可能需要考虑跨版本升级，版本兼容等问题
                    // 先访问后端是否存在更新的，看后端返回啥信息，比如更新的内容，如果有更新则下载文件
                    // 简单弹框升级
                    AppDialogConfig config = new AppDialogConfig(context);
                    config.setTitle("下载并安装更新最新版本")
                            .setOk("升级")
                            .setContent(updateInfo)
                            .setOnClickOk(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    new AppUpdater.Builder()
                                            .setUrl(downloadUrl)
                                            .build(getAppContext())
                                            .start();
                                    AppDialog.INSTANCE.dismissDialog();
                                }
                            });
                    AppDialog.INSTANCE.showDialog(config);
                }
            }
            if (onResponse != null) {
                onResponse.close();
            }
        }).get();
    }


    /**
     * 显示位置信息
     */
    public void startLocationService() {
        // start service
        final Intent serviceIntent = new Intent(MainActivity.this, LocationService.class);
        bindService(serviceIntent, mConnection, Context.BIND_AUTO_CREATE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            getBaseContext().startForegroundService(serviceIntent);
        } else
            startService(new Intent(getBaseContext(), LocationService.class));

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    private TextView btnCancel;
    private TextView btnSubmit;
    private RelativeLayout boxUserName;
    private EditText editUserName;
    private RelativeLayout boxPassword;
    private EditText editPassword;

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        switch (id) {
//            case R.id.action_login:
//                FullScreenDialog.show(new OnBindView<FullScreenDialog>(R.layout.layout_full_login) {
//                    @Override
//                    public void onBind(FullScreenDialog dialog, View v) {
//                        btnCancel = v.findViewById(R.id.btn_cancel);
//                        btnSubmit = v.findViewById(R.id.btn_submit);
//                        boxUserName = v.findViewById(R.id.box_userName);
//                        editUserName = v.findViewById(R.id.edit_userName);
//                        boxPassword = v.findViewById(R.id.box_password);
//                        editPassword = v.findViewById(R.id.edit_password);
//                        initFullScreenLoginDemo(dialog);
//                    }
//                });
//                break;
            case R.id.action_settings:
//                inputUserId();
                Intent settingIntent = new Intent(MainActivity.this, SettingsActivity.class);
                startActivity(settingIntent);
                break;
            case R.id.action_history:
                Intent intent4 = new Intent(MainActivity.this, HistoryActivity.class);
                startActivity(intent4);
                break;
            case R.id.action_about:
                about2();
                break;
        }

        return super.onOptionsItemSelected(item);
    }

    public void hideIME(@Nullable EditText editText) {
        if (editText != null) {
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(editText.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        } else {
            View view = getCurrentFocus();
            if (view != null) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

    //获取屏幕宽度
    public int getDisplayWidth() {
        Display disp = getWindowManager().getDefaultDisplay();
        Point outP = new Point();
        disp.getSize(outP);
        return outP.x;
    }

    private void initFullScreenLoginDemo(final FullScreenDialog fullScreenDialog) {
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fullScreenDialog.dismiss();
            }
        });

        btnCancel.setText("取消");
        btnSubmit.setText("下一步");
        btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isNull(editUserName.getText().toString().trim())) {
                    hideIME(null);
                    TipDialog.show("请输入账号", TipDialog.TYPE.WARNING);
                    return;
                }

                boxUserName.animate().x(-getDisplayWidth()).setDuration(300);
                boxPassword.setX(getDisplayWidth());
                boxPassword.setVisibility(View.VISIBLE);
                boxPassword.animate().x(0).setDuration(300);

                editPassword.setFocusable(true);
                editPassword.requestFocus();

                btnCancel.setText("上一步");
                btnCancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        boxUserName.animate().x(0).setDuration(300);
                        boxPassword.animate().x(getDisplayWidth()).setDuration(300);

                        editUserName.setFocusable(true);
                        editUserName.requestFocus();

                        initFullScreenLoginDemo(fullScreenDialog);
                    }
                });

                btnSubmit.setText("登录");
                btnSubmit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        hideIME(null);
                        if (isNull(editPassword.getText().toString().trim())) {
                            TipDialog.show("请输入密码", TipDialog.TYPE.WARNING);
                            return;
                        }
                        WaitDialog.show("登录中...");
                        runOnMainDelayed(new Runnable() {
                            @Override
                            public void run() {
                                TipDialog.show("登录成功", TipDialog.TYPE.SUCCESS).setDialogLifecycleCallback(new DialogLifecycleCallback<WaitDialog>() {
                                    @Override
                                    public void onDismiss(WaitDialog dialog) {
                                        fullScreenDialog.dismiss();
                                    }
                                });
                            }
                        }, 2000);
                    }
                });
            }
        });
    }

    public void runOnMainDelayed(Runnable runnable, long time) {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                runOnMain(runnable);
            }
        }, time);
    }

    public boolean isAlive = false;                                         //当前Activity是否处于存活状态

    public void runOnMain(Runnable runnable) {
        if (!isAlive) {
            return;
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                runnable.run();
            }
        });
    }

    public void about() {
        AppDialogConfig config = new AppDialogConfig(context);
        config.setTitle("当前版本")
                .setOk("确定")
                .setHideCancel(true)
                .setContent("2.0-2021.05.30")
                .setOnClickOk(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        AppDialog.INSTANCE.dismissDialog();
                    }
                });
        AppDialog.INSTANCE.showDialog(config);
    }

    public void about2() {
        Intent intent4 = new Intent(MainActivity.this, AboutActivity.class);
        startActivity(intent4);
    }

    /**
     * 使用之前必须输入自己的手机号码
     */
    @Deprecated
    private void inputUserId() {
        AppDialogConfig config = new AppDialogConfig(context, R.layout.input_userid);
        View dialogView = config.getDialogView();
        EditText value = (EditText) dialogView.findViewById(R.id.value);
//        https://blog.csdn.net/u010746364/article/details/51489020
//        value.setFilters(new InputFilter[]{new InputFilterMinMax("1", "12")});
        InputFilter[] filters = {new InputFilter.LengthFilter(11)};
        value.setFilters(filters); //表示最大输入10个字符。
        config.setOkId(R.id.find)
                .setCancelId(R.id.cancel)
                .setOnClickOk(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        Editable text = value.getText();
                        if (text != null && text.length() > 0) {
                            String s = text.toString();
                            long userIdLong = Long.parseLong(s);
                            KVUtils.get().putLong(Constant.USER_ID, userIdLong);
                            Intent intent = new Intent(Constant.BroadCast.INTERVAL);
                            intent.putExtra(Constant.USER_ID, userIdLong);
                            sendBroadcast(intent);
                            AppDialog.INSTANCE.dismissDialog();
                        } else {
                            Toast.makeText(MainActivity.getAppContext(), "请输入手机号码", Toast.LENGTH_SHORT).show();
                        }
                    }
                }).setOnClickCancel(v -> {
            AppDialog.INSTANCE.dismissDialog();
        });
        AppDialog.INSTANCE.showDialog(config);
    }

    @Override
    public boolean onSupportNavigateUp() {
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
        return NavigationUI.navigateUp(navController, appBarConfiguration)
                || super.onSupportNavigateUp();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(mConnection);
    }


    /**
     * 调用此方法判断是否拥有权限
     */
    private void initPermissions() {
        if (lacksPermission(permissions)) {//判断是否拥有权限
            //请求权限，第二参数权限String数据，第三个参数是请求码便于在onRequestPermissionsResult 方法中根据code进行判断
            ActivityCompat.requestPermissions(this, permissions, OPEN_SET_REQUEST_CODE);
        } else {
            //拥有权限执行操作
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
//            开启后台权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
                    ACCESS_BACKGROUND_LOCATION}, 101);
        } else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 101);
        }

        if (!GpsUtil.isOPen(this)) {
            //简单弹框
            AppDialogConfig config = new AppDialogConfig(context);
            config.setTitle("开启位置服务")
                    .setOk("允许")
                    .setContent("为了提高精准度，需要开启位置服务")
                    .setOnClickOk(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            // 去开启位置服务
                            GpsUtil.openGPS(getAppContext());
                            AppDialog.INSTANCE.dismissDialog();
                        }
                    });
            AppDialog.INSTANCE.showDialog(config);
        }
    }


    /**
     * 如果返回true表示缺少权限
     *
     * @param permissions
     * @return
     */
    public boolean lacksPermission(String[] permissions) {
        for (String permission : permissions) {
            //判断是否缺少权限，true=缺少权限
            if (ContextCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                return true;
            }
        }
        return false;
    }


    //权限数组（申请定位）
    private String[] permissions = new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS};

    //返回code
    private static final int OPEN_SET_REQUEST_CODE = 100;

}